package spring.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import spring.domain.Operand;
import spring.model.service.CalculatorService;

/*
 * MultiActionController 구현
 * 1. MultiAction controller 상속
 * 2. controller 메소드들 구현
 * 		return type : 
 * 			ModelAndView - Model and View 정보 둘다 return
 * 			String 		 - View 정보만 return
 * 			Map			 - Model만 return (View - 요청한 url)
 * 			void		 - Model이 없고 View는 요청 url을 사용할 때
 */
public class CalculatorController extends MultiActionController {
	
	private CalculatorService service;
	public CalculatorController(CalculatorService service) {
		this.service = service;
	}
	public ModelAndView plus(HttpServletRequest request, HttpServletResponse response) {
		/*
		 * 컨트롤러 로직
		 * 1. 요청파라미터 조회
		 * 2. Business Logic 호출(Model 호출)
		 * 3. 응답 처리(View 호출)
		 */
		String operand1 = request.getParameter("operand1");
		String operand2 = request.getParameter("operand2");
		ModelAndView mv = null;
		try{
			//1
			int op1 = Integer.parseInt(operand1);
			int op2 = Integer.parseInt(operand2);
			//2
			int result = service.plus(op1, op2);
			//3
			//매개변수 1.View이름 / 2.Attribute 이름 / 3.Attribute(request scope)
			mv = new ModelAndView("/result.jsp", "result", result);
			
		}catch(NumberFormatException ne) {
			mv = new ModelAndView("/error.jsp", "message", "오류발생");		
		}
		return mv;
	}
	
	public ModelAndView minus(HttpServletRequest request, HttpServletResponse response,Operand op) {
		int result = service.minus(op);
		return new ModelAndView("/result.jsp", "result", result);
	}
}
